package edu.sandau.app.basic.service.impl;

import edu.sandau.app.basic.domain.Cart;
import edu.sandau.app.basic.domain.CartExample;
import edu.sandau.app.basic.mapper.CartMapper;
import edu.sandau.app.basic.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    
    @Autowired
    private CartMapper cartMapper;
    
    @Override
    public List<Cart> getUserCart(Long userId) {
        CartExample example = new CartExample();
        example.createCriteria().andUserIdEqualTo(userId);
        return cartMapper.selectByExample(example);
    }
    
    @Override
    @Transactional
    public int addToCart(Cart cart) {
        // 检查该用户是否已经添加过该菜品
        CartExample example = new CartExample();
        example.createCriteria()
                .andUserIdEqualTo(cart.getUserId())
                .andDishIdEqualTo(cart.getDishId());
        List<Cart> existingCarts = cartMapper.selectByExample(example);
        
        if (!existingCarts.isEmpty()) {
            // 如果已存在，更新数量
            Cart existingCart = existingCarts.get(0);
            existingCart.setQuantity(existingCart.getQuantity() + cart.getQuantity());
            existingCart.setUpdateTime(new Date());
            return cartMapper.updateByPrimaryKeySelective(existingCart);
        } else {
            // 如果不存在，添加新记录
            cart.setCreateTime(new Date());
            cart.setUpdateTime(new Date());
            return cartMapper.insertSelective(cart);
        }
    }
    
    @Override
    @Transactional
    public int updateCartItem(Cart cart) {
        cart.setUpdateTime(new Date());
        return cartMapper.updateByPrimaryKeySelective(cart);
    }
    
    @Override
    @Transactional
    public int deleteCartItem(Long cartId) {
        return cartMapper.deleteByPrimaryKey(cartId);
    }
    
    @Override
    @Transactional
    public int clearUserCart(Long userId) {
        CartExample example = new CartExample();
        example.createCriteria().andUserIdEqualTo(userId);
        return cartMapper.deleteByExample(example);
    }
    
    @Override
    public Cart getCartItem(Long userId, Long dishId) {
        CartExample example = new CartExample();
        example.createCriteria()
                .andUserIdEqualTo(userId)
                .andDishIdEqualTo(dishId);
        List<Cart> carts = cartMapper.selectByExample(example);
        return carts.isEmpty() ? null : carts.get(0);
    }
}

